#!/bin/bash

TOPDIR=`readlink -f $0`
TOPDIR_FILE_NAME=`basename $TOPDIR`
TOPDIR=`dirname $TOPDIR`

source .config

DEFAULT_CHIP=${CONFIG_DEFAULT_STM32_DEVICE}
FIRMWARE_PATH=${CONFIG_FIRMWARE_PATH}
FIRMWARE_BUILD_PATH=${FIRMWARE_PATH}/build
FIRMWARE_BIN_PATH=${FIRMWARE_PATH}/bin
BOOTLOADER_PATH=${CONFIG_BOOTLOADER_PATH}
BOOTLOADER_BUILD_PATH=${BOOTLOADER_PATH}/build
BOOTLOADER_BIN_PATH=${BOOTLOADER_PATH}/bin
FIRMWARE_OFFSET=${CONFIG_DEFAULT_FIRMWARE_OFFSET}
DEBUGER_TYPE=${CONFIG_DEFAULT_DEBUGER_DEVICE}
TOOL_PATH=${CONFIG_COMPILE_TOOL_PATH}
PROJECT_NAME=${CONFIG_DEFAULT_PROJECT_NAME}
MODULE_NAME=${CONFIG_DEFAULT_MODULE_NAME}
DEBUGER_PATH=${CONFIG_DEFAULT_DEBUGER_PATH}
COMPILE_ENV=${CONFIG_DEFAULT_COMPILE_ENV}
COMPILE_TOOLCHAIN_TOOL=${CONFIG_COMPILE_TOOLCHAIN_PATH}

if [ 2 != $# ]; then
    echo "parameters number error!"
    exit -1
elif [ 'boot' != $2 ] && [ 'app' != $2 ]; then
    echo "project parameters type error!"
    exit -2
elif [ 'build' != $1 ] && [ 'flash' != $1 ] && [ 'clean' != $1 ]; then
    echo "process type error!"
    exit -3
else
    PROCESS_TYPE=$1
    FIRMWARE_TYPE=$2
fi

BOOTLOADER_BASE=0x08000000

if [ ${MODULE_NAME} == "ECU" ]; then
    FIRMWARE_DEFAULT_OFFSET=0x10000
    CRC_INSERT_FLAG=1
elif [ ${MODULE_NAME} == "VCU" ]; then
    FIRMWARE_DEFAULT_OFFSET=0x6000
    CRC_INSERT_FLAG=2
elif [[ ${MODULE_NAME} == "BSU" || ${MODULE_NAME} == "CGS" ]]; then
    FIRMWARE_DEFAULT_OFFSET=0x1000
fi

if [ 'app' == ${FIRMWARE_TYPE} ]; then
    EXECUTABLE_FILE_PATH=${FIRMWARE_BIN_PATH}
    BUILD_PATH=${FIRMWARE_BUILD_PATH}
    BIN_PATH=${FIRMWARE_BIN_PATH}
    COMOM_PATH=${FIRMWARE_PATH}
    TAGET_NAME=Firmware
    if [ -z ${FIRMWARE_OFFSET} ]; then
        DOWNLOAD_POS=$((${BOOTLOADER_BASE}+${FIRMWARE_DEFAULT_OFFSET}))
    else
        DOWNLOAD_POS=$((${BOOTLOADER_BASE}+${FIRMWARE_OFFSET}))
    fi
elif [ 'boot' == ${FIRMWARE_TYPE} ]; then
    DOWNLOAD_POS=${BOOTLOADER_BASE}
    BUILD_PATH=${BOOTLOADER_BUILD_PATH}
    BIN_PATH=${BOOTLOADER_BIN_PATH}
    EXECUTABLE_FILE_PATH=${BOOTLOADER_BIN_PATH}
    COMOM_PATH=${BOOTLOADER_PATH}
    TAGET_NAME=Bootloader
    CRC_INSERT_FLAG=0
else
    echo "fatal error!!!"
    exit -3
fi

VERSION_INI=$COMOM_PATH/version.ini
LD_FILE=$(ls ${COMOM_PATH}/*.ld)
AUTOR_GENERATER_PATH=$COMOM_PATH/auto_generater

echo "tool_path             => $TOOL_PATH"
echo "chip                  => $DEFAULT_CHIP"
echo "firmware_build_path   => $FIRMWARE_BUILD_PATH"
echo "bootloader_build_path => $BOOTLOADER_BUILD_PATH"
echo "firmware_bin_path     => $FIRMWARE_BIN_PATH"
echo "bootloader_bin_path   => $BOOTLOADER_BIN_PATH"
echo "debuger_type          => $DEBUGER_TYPE"
echo "project_name          => $PROJECT_NAME"
echo "firmware_offset       => $FIRMWARE_OFFSET"
echo "debuger_path          => $DEBUGER_PATH"
echo "compile_env           => $COMPILE_ENV"
echo "compile_toolchain     => $COMPILE_TOOLCHAIN_TOOL"
echo "LD_FILE               => $LD_FILE"

if [ $PROCESS_TYPE == 'clean' ]; then
    if [ -d $BIN_PATH ];then
        rm -rf $BIN_PATH
    fi
    if [ -d $BUILD_PATH ];then
        rm -rf $BUILD_PATH
    fi
    
	if [ -d $AUTOR_GENERATER_PATH ];then
		rm -rf $AUTOR_GENERATER_PATH
	fi
elif [ $PROCESS_TYPE == 'build' ]; then
    if [ ! -d $BUILD_PATH ];then
        mkdir $BUILD_PATH
    else
        rm -rf $BUILD_PATH/*.bin
        rm -rf $BUILD_PATH/*.hex
        rm -rf $BUILD_PATH/*.map
        rm -rf $BUILD_PATH/*.elf
    fi

    if [ ! -d $BIN_PATH ];then
        mkdir $BIN_PATH
    else
        rm -r $BIN_PATH/*
    fi
    
    source $TOOL_PATH/ld_info.rc
    source $TOOL_PATH/version_info.rc
    
    wl_version_info_update  $VERSION_INI
    ld_info_update $LD_FILE
    if [ $WL_VERSION_OFFSET == $LD_VERSION_OFFSET ];then
        echo "ld check pass"
    else
        echo WL_VERSION_OFFSET = $WL_VERSION_OFFSET
        echo LD_VERSION_OFFSET = $LD_VERSION_OFFSET
        echo "ld check failed,please update ld file:$LD_FILE!!!!!!"
        exit -1
    fi

    $TOOL_PATH/pre_build.sh $AUTOR_GENERATER_PATH $VERSION_INI
    process_result=$?
    if [ 0 != $process_result ];then
        echo "pre_build failed!!!"
        exit -1;
    fi
    
    PROJECT_NAME=`echo $WL_PROJECT | awk '{print toupper($0)}'`

    cd ${BUILD_PATH}
    if [ "$(uname -o)" = "Msys" ]; then
        cmake .. -G "MinGW Makefiles" -D PROJECT_NAME=$PROJECT_NAME
    else
        cmake .. -D PROJECT_NAME=$PROJECT_NAME
    fi

    echo "starting make -j$(nproc)...."
    make -j$(nproc)

    process_result=$?
    if [ 0 != $process_result ];then
        echo "make failed!!!"
        exit -1;
    fi

    cd $COMPILE_TOOLCHAIN_TOOL
    $COMPILE_TOOLCHAIN_TOOL/post_build.sh $VERSION_INI $BUILD_PATH $BIN_PATH $TAGET_NAME $CRC_INSERT_FLAG $TOOL_PATH
    process_result=$?
    if [ 0 != $process_result ];then
        echo "post_build failed!!!"
        exit -1;
    fi
    echo "build success!"
    
elif [ $PROCESS_TYPE == 'flash' ]; then
    FARMWARE_HEX=$(ls ${EXECUTABLE_FILE_PATH}/${PROJECT_NAME}*.hex)
    FARMWARE_BIN=$(ls ${EXECUTABLE_FILE_PATH}/${PROJECT_NAME}*.bin)

    echo "<===  Start downloading ${FIRMWARE_TYPE} to ${DOWNLOAD_POS}  ===> "
    echo ""

    if [ 'stlink' == ${DEBUGER_TYPE} ]; then
        echo "download ${FARMWARE_BIN} use ${DEBUGER_TYPE}"
        st-info --descr
        st-flash write ${FARMWARE_BIN} ${DOWNLOAD_POS}
    elif [ 'jlink' == ${DEBUGER_TYPE} ]; then
        JLINK_SCRIPT_FILE=jlink_config.txt

        rm -f ${JLINK_SCRIPT_FILE}
        touch ${JLINK_SCRIPT_FILE}

        # config download order
        echo "si 1" >> ${JLINK_SCRIPT_FILE}              # choose swd download
        echo "speed 1000" >> ${JLINK_SCRIPT_FILE}
        echo "device ${DEFAULT_CHIP}" >> ${JLINK_SCRIPT_FILE}
        echo "r" >> ${JLINK_SCRIPT_FILE}
        echo "h" >> ${JLINK_SCRIPT_FILE}
        echo "loadfile ${FARMWARE_HEX}" >> ${JLINK_SCRIPT_FILE}
        echo "r" >> ${JLINK_SCRIPT_FILE}
        echo "g" >> ${JLINK_SCRIPT_FILE}
        echo "qc" >> ${JLINK_SCRIPT_FILE}

        # execute download operation
        if [ 'linux' == ${COMPILE_ENV} ]; then
            JLinkExe -commandfile ${JLINK_SCRIPT_FILE}
        elif [ 'win' == ${COMPILE_ENV} ]; then
            JLink -commandfile ${JLINK_SCRIPT_FILE}
        fi
        echo "jlink debuger!"
    elif [ 'o-dap' == ${DEBUGER_TYPE} ]; then
        echo "download ${FARMWARE_HEX} use ${DEBUGER_TYPE}"
        openocd -f ${DEBUGER_PATH}/interface/cmsis-dap.cfg \
                -f ${DEBUGER_PATH}/target/stm32f1x.cfg     \
                -c init \
                -c halt \
                -c "program ${FARMWARE_HEX} verify" \
                -c reset \
                -c exit
    else
        echo "debuger error!"
    fi 

    echo ""
    echo "<===  Finish downloading ${FIRMWARE_TYPE}  ===>"

    exit 0

fi

